package com.wuze.cloud.util;

import com.wuze.cloud.exception.SysGlobalException;
import org.apache.commons.mail.HtmlEmail;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Random;
import java.util.regex.Pattern;

import static com.wuze.cloud.enums.SysGlobalExceptionEnum.CODE_SEND_FAIL;

/**
 * @author: wuze
 * @description:
 * @date: 2023/02/16
 */
@Component
public class MailUtil {

    @Value("${email.config.code}")
    private String pwd;
    @Value("${email.config.sender}")
    private String sender;
    @Value("${email.config.host}")
    private String host;
    @Value("${email.config.name}")
    private String name;



    /**
     * 验证邮箱格式
     * @param email
     * @return
     */
    public boolean isEmail(String email) {
        if (email == null || email.length() < 1 || email.length() > 256) {
            return false;
        }
        Pattern pattern = Pattern.compile("^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$");
        return pattern.matcher(email).matches();
    }



    /**
     * 发送验证码
     * @param email
     * @return
     */
    public void sendAuthCodeEmail(String email,String code) {
        try {
            HtmlEmail mail = new HtmlEmail();
            /*发送邮件的服务器 126邮箱为smtp.126.com,163邮箱为smtp.163.com，QQ为smtp.qq.com*/
            mail.setHostName(host);
            /*不设置发送的消息有可能是乱码*/
            mail.setCharset("UTF-8");
            /*IMAP/SMTP服务的密码*/
            mail.setAuthentication(sender, pwd);
            /*发送邮件的邮箱和发件人*/
            mail.setFrom(sender, name);
            /*使用安全链接*/
            mail.setSSLOnConnect(true);
            /*接收的邮箱*/
            mail.addTo(email);
            /*验证码*/
//            String code = generateVerifyCode(6);
            /*设置邮件的主题*/
            mail.setSubject("注册验证码");
            /*设置邮件的内容*/
            mail.setMsg("【cloud-storage】尊敬的用户:你好! 您的验证码是:" + code + "，5分钟内有效。\n" +
                    "请不要把验证码泄露给其他人，如非本人操作请忽略。");
            String send = mail.send();//发送

        } catch (Exception e) {
            e.printStackTrace();
            throw new SysGlobalException(CODE_SEND_FAIL.getCode(),CODE_SEND_FAIL.getMsg());
        }

    }

    /**
     * 生成随机验证码
     * @param number 几位数
     * @return
     */

    public String generateVerifyCode(int number) {
        Random random = new Random();
        StringBuilder builder = new StringBuilder();
        for (int i = 1; i <= number; i++) {
            builder.append(random.nextInt(10));
        }
        return builder.toString();
    }

}

